<template>
  <div>
    <div class="pageheader">
      <XHeader :left-options="{showBack:false,backText:''}" :title="xheader.title"
               class="XHeader login-title"></XHeader>
    </div>
    <div class="page">
      <div class="logo_img" v-if="isSanXia">
        <img :src="sanxiaLogoPNG">
      </div>
      <div v-else-if="isXBZG">
        <div class="text">
          <span>欢迎来到智谷汇员工商城</span>
        </div>
      </div>
      <div v-else>
        <div class="text">
          <span>欢迎来到{{isTitle}}</span>
        </div>
      </div>

      <div style="margin-top: 28px">
        <!--账号登录-->
        <template v-if="isAccount">
          <div class="inputbox">
            <!--          <chimage class="icon" :src="require('@/assets/img/icon_phone.png')" mode="aspectFit"></chimage>-->
            <chimage class="icon" :src="require('@/assets/img/ic_user.png')" mode="aspectFit"></chimage>
            <input class="input" v-model.trim="phone" placeholder="请输入账号" type="text" @focusout="inputBlur" @focusin="inputFocus"/>
          </div>
          <div class="inputbox">
            <chimage class="icon" mode="aspectFit" :src="require('@/assets/img/icon_mm.png')"></chimage>
            <input class="input" v-model.trim="password" type="password" placeholder="请输入密码" @focusout="inputBlur" @focusin="inputFocus"/>
          </div>
        </template>

        <!--短信登录-->
        <template v-if="isSMS">
          <div class="inputbox">
            <chimage class="icon" :src="require('@/assets/img/icon_phone.png')" mode="aspectFit"></chimage>
            <input class="input" v-model.trim="verify_account" placeholder="请输入手机号" type="text" @focusout="inputBlur" @focusin="inputFocus"/>
          </div>

          <div class="inputbox2">
            <div class="inputbox">
              <chimage class="icon" mode="aspectFit" :src="require('@/assets/img/icon_code.png')"></chimage>
              <input class="input" v-model.trim="smsCode" type="number" placeholder="请输入验证码" @focusout="inputBlur" @focusin="inputFocus"/>
            </div>
            <div class='code_btn'>
              <span @click="getVerifyCode" ref='codeBtn'>获取验证码</span>
            </div>
          </div>
        </template>
        <!-- <div class="inputbox" wx:if="coList.length">
          <chimage class="icon" :src="require('@/assets/img/icon_phone.png')" mode="aspectFit"></chimage>
          <select v-model="coIndex" class="input">
            <option
              v-for="(item,index) in coList"
              :key="index"
              value
              class="input"
            >{{coList[coIndex].co_name}}</option>
          </select>
        </div>-->
        <div style="margin-top: 32px">
          <!--          <button class="button" :disabled="!isPhone&&!password" @click="onSubmit">登录</button>-->
          <button class="button" @click="onSubmit">登录</button>
        </div>

        <div style="margin-top: 12px">
          <div class="flex flex-space-between desc">
            <span style="color: #5FC2FF;" v-if="isSMS" @click="onAccount">账号密码登录</span>
            <span style="color: #5FC2FF;" v-if="isAccount" @click="onSMS">账号激活</span>
            <span>
              <span style="color: #351009; margin-right: 5px" @click="forgetPassword">忘记密码?</span>
              <span v-if="isSanXia || isM" style="color: #5FC2FF;" @click="onRegister">注册</span>
            </span>
          </div>
          <div class="login-tip" v-if="isAccount">首次登录请使用账号激活，激活账号并修改您的密码</div>
          <div class="login-tip" style="text-align: center; color: red" v-if="isSMS">账号激活功能只用于首次激活账号</div>
        </div>
      </div>
    </div>
    <actionsheet
      v-model="iscoList"
      :menus="coList"
      :close-on-clicking-mask="false"
      @on-click-menu="onColist"
    ></actionsheet>
    <actionsheet
      v-model="findPass"
      :menus="findPassWays"
      :close-on-clicking-mask="true"
      @on-click-menu="onFindPassWays"
    >
      <div slot="header">
        <div style="font-size: 20px; color: #0072ff">{{findPassTitle}}</div>
        <div style="color: #929191; font-size: 14px" v-if="isReset == 1 && isAccount">检测原口令为弱口令,请修改密码</div>
      </div>
    </actionsheet>
  </div>
</template>

<script>
  // import { cookie } from 'vux'
  import Account from '../../dll/account'
  import Address from '@/dll/address'
  // import Util from '@/utils/util'

  // import baseUrl from '../../baseUrl'

  import sanxiaLogoPNG from '../../assets/sanxia/sanxia_logo.png'

  import getCode from '../../mixin/getCode'

  import { mapMutations } from 'vuex'

  export default {
    name: 'login',
    mixins: [getCode],
    data () {
      return {
        xheader: {
          title: '登录'
        },

        sanxiaLogoPNG,

        co_number: null,

        isAccount: true, // 账号登录
        isSMS: false, // 短信登录
        smsCode: '', // 短信验证码
        find_type: 0, // 1 短信登陆 0 账号密码
        verify_account: '', // 手机号O

        phone: '',
        password: '',

        isPhone: false,
        iscoList: false,
        coList: [],
        coIndex: 0,
        findPass: false,
        findPassTitle: '忘记密码',
        isReset: 0,
        findPassWays: [{ label: '手机找回', value: 1 }, { label: '邮箱找回', value: 2 }]
      }
    },
    watch: {
      // phone (val, oldVal) {
      //   // if (val.length > 11) {
      //   //   this.phone = oldVal
      //   //   return
      //   // }
      //   // if (val.length <= oldVal.length) {
      //   //   return;
      //   // }
      //   if (/^\d{11}$/.test(val)) {
      //     // this.getCoCode();
      //     this.isPhone = true
      //   } else {
      //     // this.coList = [];
      //     this.isPhone = false
      //   }
      // }
    },
    created () {
      this.phone = localStorage.loginPhone || ''
      this.verify_account = localStorage.loginPhone || ''
      this.password = localStorage.loginPassword || ''
      this.init()
    },
    computed: {
      isTitle () {
        let _href = window.location.href
        let title = ''
        if (this.isSanXia) {
          title = '三峡e购员工商城'
        } else if (((/gw.ulinkmall.com/).test(_href))) {
          title = '国网商城'
        } else {
          title = '内购商城'
        }
        return title
      }
    },
    methods: {
      ...mapMutations(['setFlag']),

      // 短信登录
      onSMS () {
        this.isSMS = true
        this.isAccount = false
        this.endTimer()
        this.find_type = 1
        this.xheader.title = '账号激活'
        this.smsCode = ''
      },

      // 账号登录
      onAccount () {
        this.isSMS = false
        this.isAccount = true
        this.endTimer()
        this.find_type = 0
        this.xheader.title = '登录'
        this.smsCode = ''
      },

      init () {
        let query = this.$route.query
        if (query.ticket) {
          this.ticket = query.ticket
          this.ticketLogin()
        }
      },
      onColist (menuKey) {
        this.co_number = menuKey
        if (this.ticket) {
          this.ticketLogin()
        } else {
          this.onSubmit()
        }
      },
      loginfun () {
      },
      async ticketLogin () {
        this.$vux.loading.show({
          text: '登录中'
        })
        let res = await Account.ticketLogin(this.ticket)
        this.$vux.loading.hide()
        if (res.code == 0) {
          this.globalData.access_token = res.data.access_token
          this.globalData.userInfo = res.data.extra
          this.globalData.userInfo.avatarUrl =
            this.globalData.userInfo.avatarUrl || require('@/assets/img/dfimg.jpg')
          // cookie.set("accesstoken", res.data.access_token);
          localStorage.setItem('accesstoken', res.data.access_token)
          localStorage.setItem('userInfo', JSON.stringify(res.data.extra))
          if (res.data.extra.is_weixin == 1) {
            if (
              !res.data.extra.wxgzh_openid ||
              res.data.extra.wxgzh_id != res.data.extra.appid
            ) {
              location.href = res.data.extra.return_url
              return
            }
          }
          this.$router.replace({
            name: 'mall',
            params: { from: this.$route.params.from }
          })
        }
        if (res.code == 1005) {
          let coList = []
          for (var i in res.data) {
            coList.push({
              lable: res.data[i].co_name,
              value: res.data[i].co_number
            })
          }
          this.coList = coList
          this.iscoList = true
        }
        if (res.code == -1) {
          this.$vux.alert.show({
            title: '提示',
            content: res.msg
          })
        }
      },
      forgetPassword () {
        this.isReset = 0
        this.findPassTitle = '忘记密码'
        this.findPassWays = [
          { label: '手机找回', value: 1 },
          { label: '邮箱找回', value: 2 }
        ]
        this.findPass = true
      },
      async onFindPassWays (find_type) {
        this.$router.push({
          name: 'findPassword',
          query: { find_type: find_type, isReset: this.isReset }
        })
      },
      async onSubmit () {
        if (this.find_type === 0) {
          if (!this.phone.trim()) {
            this.$vux.toast.text('请输入账号')
            return
          }
          if (!this.password.trim()) {
            this.$vux.toast.text('请输入密码')
            return
          }
        }
        if (this.find_type === 1) {
          if (!this.verify_account.trim()) {
            this.$vux.toast.text('请输入手机号')
            return
          }
          if (!this.smsCode.trim()) {
            this.$vux.toast.text('请输入短信验证码')
            return
          }
        }
        window.scrollBy(0, 10)
        let param = {
          phone: this.phone,
          password: this.password,
          find_type: this.find_type,
          smsCode: this.smsCode,
          verify_account: this.verify_account,
          url: sessionStorage.getItem('shareUrl')
        }

        if (this.co_number) {
          param.co_number = this.co_number
        }
        this.$vux.loading.show({
          text: '登录中'
        })
        let res = await Account.login(param)
        this.$vux.loading.hide()
        if (res.code == 0) {
          this.globalData.access_token = res.data.access_token
          this.globalData.userInfo = res.data.extra
          this.globalData.userInfo.avatarUrl =
            this.globalData.userInfo.avatarUrl || require('@/assets/img/dfimg.jpg')
          // cookie.set("accesstoken", res.data.access_token);
          localStorage.setItem('accesstoken', res.data.access_token)
          localStorage.setItem('userInfo', JSON.stringify(res.data.extra))
          localStorage.loginPhone = this.phone || this.verify_account
          localStorage.loginPassword = this.password
          if (res.data.extra && parseFloat(res.data.extra.flag)) {
            this.setFlag({ flag: true, callback: this.onShowLeftArrow })
          } else {
            this.setFlag({
              flag: false,
              callback: () => {
              }
            })
          }

          if (res.data.extra.is_weixin == 1) {
            // if (
            //   !res.data.extra.wxgzh_openid ||
            //   res.data.extra.wxgzh_id != res.data.extra.appid
            // ) {
            location.href = res.data.extra.return_url
            return
            // }
          }
          this.$router.replace({
            name: 'mall',
            params: { from: this.$route.params.from }
          })

          return
        }
        if (res.code == 1005) {
          let coList = []
          for (var i in res.data) {
            coList.push({
              label: res.data[i].co_name,
              value: res.data[i].co_number
            })
          }
          this.coList = coList
          this.iscoList = true
          return
        }
        if (res.code == -9999) {
          this.isReset = 1
          this.findPassTitle = '重置密码'
          this.findPassWays = [
            { label: '手机验证', value: 1 },
            { label: '邮箱验证', value: 2 }
          ]
          this.findPass = true
          // this.$router.push({
          //   name: 'resetPassword'
          // })
        } else {
          this.$vux.alert.show({
            title: '提示',
            content: res.msg
          })
        }
      },

      // 注册
      onRegister () {
        let inviteCode = ''
        if (this.isSanXia) {
          inviteCode = '07e7a64b387505b177234eea002802024252'
        } else if (this.isM) {
          inviteCode = 'b3b49508e43e98e6ae479b016d66b0002447'
        } else {
          inviteCode = ''
        }
        this.$router.push({ name: 'register', query: { invite_code: inviteCode } })
      },

      // 如果是重庆电信就隐藏tab左上角的返回按钮
      onShowLeftArrow () {
        this.$nextTick(function () {
          if (this.isCQDX) {
            let leftArrow = document.querySelector('.left-arrow')
            if (leftArrow) {
              document.querySelector('.left-arrow').style.display = 'none'
            }
            this.setDefaultAddress()
          }
        })
      },

      // 设置默认地址
      async setDefaultAddress () {
        let address = await Address.getDefaultAddress()
        if (address.code == 0) {
          let areaInfo = (address.data.area_info).split(' ')
          let alias = (address.data.alias).split('_')
          let jddzqy = areaInfo.map((item, index) => {
            if (item) {
              return { id: alias[index], area: item }
            }
          })
          localStorage.jddzqy = JSON.stringify(jddzqy)
        }
      }
    }
  }
</script>

<style lang="less" scoped>
  body {
    background-color: #ffffff;
  }

  .page {
    box-sizing: border-box;
    padding-left: 24px;
    padding-right: 24px;
    padding-top: 58px;
    background-color: #fff;
  }

  .logo {
    height: 51px;
    width: 119px;
  }

  .text {
    margin-top: 16px;
    color: #351009;
    font-size: 34px;
    line-height: 48px;
  }

  .inputbox {
    border: 1px solid #f5f3f3;
    display: flex;
    flex-direction: row;
    align-items: center;
    box-sizing: border-box;
    padding: 15px 12px;
  }

  .inputbox .icon {
    width: 26px;
    height: 26px;
  }

  .inputbox .icon + .input {
    margin-left: 8px;
  }

  .inputbox .input {
    font-size: 17px;
    color: #351009;
    letter-spacing: 1.06px;
    line-height: 24px;
    height: 24px;
    flex: 1;
  }

  .inputbox + .inputbox {
    margin-top: 12px;
  }

  .button {
    height: 44px;
    font-size: 16px;
    line-height: 44px;
  }

  .des {
    font-size: 15px;
  }

  .logo_img {
    img {
      max-width: 100%;
    }
  }

  .login-tip {
    margin: 16px 0;
    font-size: 14px;
    color: #9a9a9a;
  }

  .inputbox2 {
    margin: 12px 0;
    display: flex;
    flex-direction: row;
    align-items: center;
    box-sizing: border-box;
  }

  .inputbox2 > .inputbox {
    flex: 1
  }

  .inputbox2 .inputbox .input {
    width: 100px;
  }

  .code_btn {
    border: 1px solid #f5f3f3;
    height: 58px;
    border-left-style: none;
    line-height: 58px;
    font-size: 15px;
    background-color: #f5f3f3;
    text-align: center;
    padding: 0 8px;
  }

  .code_btn span {
    user-select: none;
    -ms-user-select: none;
    -webkit-user-select: none;
    -moz-user-select: none;
    -webkit-tap-highlight-color: transparent;
  }

  /deep/ .login-title {
    /deep/ .vux-header-title {
      height: auto !important;
      padding: 20px 0 !important;
      font-size: 20px !important;
      letter-spacing: 2px !important;
    }
  }
</style>
